<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      size="small"
      :inline="true"
    >
      <el-form-item
        label="小区名称"
        prop="communityName"
      >
        <el-input
          v-model="communityName"
          placeholder="请输入小区名称"
          maxlength="32"
          show-word-limit
          clearable
          @keyup.enter.native="getList"
        />
      </el-form-item>
      <el-form-item
        label="小区编码"
        prop="communityCode"
      >
        <el-input
          v-model="communityCode"
          placeholder="请输入小区编码"
          maxlength="32"
          show-word-limit
          clearable
          @keyup.enter.native="getList"
        >
          <template slot="prepend">COMMUNITY_</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getList"
        >搜索
        </el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row
      :gutter="10"
      class="mb8"
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate(multipleSelection[0])"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="delConfirm(ids)"
        >删除
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport()"
        >导出当前页
        </el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportAll"
        >导出全部
        </el-button>
      </el-col> -->
      <right-toolbar
        :show-search.sync="showSearch"
        @queryTable="getList()"
      />
    </el-row>

    <el-table
      v-loading="loading"
      :data="Communitys"
      :row-key="Communitys.communityId"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        type="selection"
        align="center"
        width="50"
      />
      <el-table-column
        width="50"
        label="序号"
        type="index"
        :index="indexMethod"
        align="center"
      />
      <el-table-column
        align="center"
        prop="communityName"
        label="小区名称"
        width="200"
      />
      <el-table-column
        align="center"
        prop="communityCode"
        label="小区编码"
        width="265"
      />
      <el-table-column
        align="center"
        prop="communityProvenceCode"
        label="省"
        width="120"
      />
      <el-table-column
        align="center"
        prop="communityCityCode"
        label="市区"
        width="120"
      />
      <el-table-column
        align="center"
        prop="communityTownCode"
        label="县区"
        width="100"
      />
      <el-table-column
        align="center"
        prop="communityDetailedAddress"
        label="小区地址"
      />
      <el-table-column
        align="center"
        prop="createTime"
        label="创建时间"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        prop="updateTime"
        label="修改时间"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="备注"
        align="center"
        prop="remark"
      ></el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleUpdate(scope.row)"
          >更换物业
          </el-button>
          <el-button
            v-if="scope.row.parentId !== 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="delConfirm(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page.sync="curr"
      :page-sizes="[1, 5, 10, 20]"
      :page-size.sync="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total.sync="total"
      @size-change="getList"
      @current-change="getList"
    />

    <!-- 添加或修改小区对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      ref="formData"
    >
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="小区名称"
              prop="communityName"
            >
              <el-input
                v-model="formData.communityName"
                placeholder="小区名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="小区地址"
              prop="area"
            >
              <el-cascader
                v-model="formData.areas"
                :options="area"
                :props="optionProps"
              ></el-cascader>
              <!-- @change="handleChange" -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item
              label="详细地址"
              prop="communityDetailedAddress"
            >
              <el-input
                v-model="formData.communityDetailedAddress"
                type="textarea"
                placeholder="请输入备注"
                clearable
                minlength="5"
                maxlength="64"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item
              label="备注"
              prop="remark"
            >
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="请输入备注"
                clearable
                minlength="5"
                maxlength="128"
                show-word-limit
                rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel('formData')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request';
// 时间转换类
import { parseTime, copyObj } from '@/utils'
// 增删查改的请求
import {
  resultResolve,
  addCommunity,
  updateCommunity,
  deleteCommunity,
  listCommunity,
  getAreaTree,
} from '@/api/community'
// 登录信息
import store from '@/store'
import { getToken } from '@/utils/auth'

export default {
  name: 'Index',
  data () {
    return {
      // 加载层
      loading: true,
      // 多选中id数组
      ids: [],
      // 小区数据集合
      Communitys: [],
      // 多选集合
      multipleSelection: [],
      // 多选禁用
      multiple: true,
      // 单选禁用
      single: true,
      // 搜索表单展示
      showSearch: true,
      // 表单验证规则
      rules: {},
      // 模糊查询小区编码
      communityCode: '',
      // 模糊查询小区名称
      communityName: '',
      // 分页初始页
      curr: 1,
      // 分页大小
      size: 10,
      // 分页数据总条数
      total: 10,
      // 表单弹出层标题
      title: '添加小区',
      // 弹出层默认隐藏
      open: false,
      // 默认表单为新增
      isAdd: true,
      // 表单数据
      formData: {
        areas: [],
        communityId: '',
        communityProvenceCode: '',
        communityCityCode: '',
        communityTownCode: '',
        communityDetailedAddress: '',
        communityName: '',
        remark: '',
        createBy: '',
        updateBy: ''
      },
      area: [],
      optionProps: {
        expandTrigger: 'hover',
        label: 'name',
        value: 'code',
        children: 'areas'
      }
    }
  },
  created () {
    this.getList()
    this.loadArea()
  },
  methods: {
    // 异步查询小区数据
    async getList () {
      this.loading = true
      const param = {
        'curr': this.curr,
        'size': this.size,
        'communityCode': this.communityCode,
        'communityName': this.communityName
      }
      const res = await listCommunity(param)
      this.Communitys = res.data.records
      this.total = res.data.total
      this.loading = false
    },
    async loadArea () {
      let res = await getAreaTree();
      this.area = res.data
    },
    // handleChange (node) {
    //   console.log(node)
    //   this.formData.communityProvenceCode = node[0]
    //   this.formData.communityCityCode = node[1]
    //   this.formData.communityTownCode = node[2]
    //   console.log(node)
    // },
    // 点击新增按钮开启弹窗
    handleAdd () {
      this.isAdd = true
      this.title = '添加小区'
      this.open = true
      // 清空表单数据
      this.formData = {
        areas: [],
        communityId: '',
        communityProvenceCode: '',
        communityCityCode: '',
        communityTownCode: '',
        communityDetailedAddress: '',
        communityName: '',
        remark: '',
        createBy: '',
        updateBy: ''
      }
    },
    // 点击修改回填数据开启弹窗
    handleUpdate (row) {
      this.isAdd = false
      this.title = '修改小区'
      this.open = true
      // this.formData = JSON.parse(JSON.stringify(row))
      request({
        url: `/zyCommunity/getInfo/?id=${row.communityId}`,
        method: 'get',
      }).then(res => {
        let data = { ...res.data };
        let areas = [Number(data.communityProvenceCode), Number(data.communityCityCode), Number(data.communityTownCode)]
        copyObj(data, this.formData);
        this.formData.areas = areas
        // console.log("修改获取 详情值", this.formData)
      })
    },
    // 多选状态改变
    handleSelectionChange (val) {
      this.multipleSelection = val
      this.ids = val.map(data => data.communityId)
      this.single = val.length !== 1
      this.multiple = !val.length
    },
    // 重置查询
    resetQuery () {
      this.communityName = ''
      this.communityCode = ''
      this.curr = 1
      this.size = 10
      this.getList()
    },
    // 删除确认
    delConfirm (row) {
      const param = row.communityId || this.ids
      this.$confirm('此操作将永久删除选中的数据, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(param)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除方法
    async handleDelete (param) {
      const res = await deleteCommunity(param)
      // 处理结果（响应弹窗）
      resultResolve(res, this)
    },
    // 提交新增/修改数据
    async submitForm () {
      let res = ''
      // 新增
      if (this.isAdd) {
        this.formData.createBy = store.getters.name
        res = await addCommunity(this.formData)
      } else {
        this.formData.updateBy = store.getters.name
        let formData = this.formData
        formData.communityProvenceCode = formData.areas[0]
        formData.communityCityCode = formData.areas[1]
        formData.communityTownCode = formData.areas[2]
        res = await updateCommunity(this.formData)
      }
      resultResolve(res, this)
      this.cancel()
    },
    // 取消/关闭弹出层清空表单
    cancel (formName) {
      this.open = false
      this.formData = {
        communityName: '',
        remark: '',
        createBy: '',
        updateBy: '',
        area: '',
      }
    },
    // 导出当页数据
    handleExport () {
      const param = {
        'curr': this.curr,
        'size': this.size,
        'communityCode': this.communityCode,
        'communityName': this.communityName,
        'Authorization': getToken()
      }
      console.log("导出地址", param);
      location.href = 'http://10.7.245.87:8080/zyCommunity/export?' + this.$qs.stringify(param)
    },
    // 导出全部数据
    handleExportAll () {
      const param = {
        'curr': 1,
        'size': this.total,
        'Authorization': getToken()
      }
      location.href = `${process.env.VUE_APP_BASE_API}/zyCommunity/export?` + this.$qs.stringify(param)
    },
    // 时间格式化
    parseTime (time) {
      return parseTime(Date.parse(time))
    },
    // 修改序号
    indexMethod (index) {
      index = (index + 1) + (this.curr - 1) * this.size
      return index
    }

  }
}
</script>

